import java.io.*;

public class CSVWriter {
	
	static String header = "Name,Date,Session name,Test type,MTS,Delay,Progress Bar, # Exemplars,Tokens types,Reward,Question #,Delay,Correct,Latency Between Sample and Comparison, Latency to Answer";
	Writer output = null;
	File file = null;
	
	
	public File nameFile(String path){
		File file = new File(path);
		if(file.exists()){
			System.out.println("Created a new file.");
			char[] dst = new char[path.length()-4];
			path.getChars(0, path.length()-4, dst, 0);//remove the .csv root.
			String newpath = new String(dst);
			newpath+="1.csv";
			file = nameFile(newpath);
		}
		else{
			path+=".csv";
		}
		return file;
	}
	
	public CSVWriter (String path) throws IOException{
		file = nameFile(path);
		output = new BufferedWriter(new FileWriter(file));
		this.write(header);
		
	}

	/**
	 * Example
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String path = "C:\\TEMP\\test1.csv";
		CSVWriter writer = new CSVWriter(path);
		writer.write(header);
		writer.write("James Madison,04/02/2012,Cheese,Type,.,.,.,.,.,.,.,.");
		writer.close();
	}
	
	/**
	 * Writes into a file.
	 * @param values string to be written.
	 * @throws IOException
	 */
	public void write(String values) throws IOException{
		output.append(values);
		output.append("\n");
		output.flush();
	}
	
	public void append(String values) throws IOException{
		output.append(values);
		output.flush();
	}
	
	/**
	 * Closes the CVS file
	 * @throws IOException
	 */
	public void close() throws IOException{
		output.close();
	}

}
